﻿namespace Contoso.ActiveDirectory {

    #region Usings
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.DirectoryServices;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    #endregion

    /// <summary>
    /// A DNS MX record, an definition for email systems
    /// </summary>
    [Serializable]
    public class DNSMXRecord : DNSResourceRecord {

        #region Members

        /// <summary>
        /// A number between 0 and 65535 that indicates the mail exchange server’s priority with respect to the other mail exchange servers. 
        /// Lower numbers are given preference to servers that are referenced in mail exchanger (MX) resource records with higher priority numbers. 
        /// The highest priority or preference for a mail exchange server is granted when a value of zero (0) is used.
        /// Where more than one mail exchanger (MX) resource record is present, the mailer attempts delivery to the mail exchange server with the lowest preference number first. 
        /// If delivery fails, the mail exchange server with the next highest preference number is tried.
        /// If two or more mail exchange servers share the same preference number, the mailer tries the mail exchange servers with the same number at random.
        /// </summary>
        public ushort Priority { get; private set; }

        /// <summary>
        /// The single-part name for a mail exchanger in this zone. 
        /// If you need to add a name here that contains a period (.) to indicate the name of an additional domain level, first add the additional 
        /// domain separately in DNS Manager and then add a new mail exchanger (MX) resource record there as a single-part name.
        /// </summary>
        public string TargetName { get; private set; }
        #endregion

        #region Constructor
        public DNSMXRecord() {
            this.Initialize();
            this.ProcessResults();
        }

        public DNSMXRecord(DNSResourceRecord parentRecord) {
            parentRecord.ShallowCopy<DNSResourceRecord, DNSMXRecord>(this);
            this.ProcessResults();
        }

        public DNSMXRecord(DirectoryEntry directoryEntry, bool destroyInputObject = true)
            : base(directoryEntry, destroyInputObject) {
            if (this.GetType().Name == typeof(DNSMXRecord).Name) {
                this.Attributes = null;
            }
        }

        public DNSMXRecord(SearchResult result, bool destroyInputObject = true)
            : base(result, destroyInputObject) {
                if (this.GetType().Name == typeof(DNSMXRecord).Name) {
                this.Attributes = null;
            }
        }
        #endregion

        #region Methods
        protected override void Initialize() {
            this.TargetName = string.Empty;
        }

        internal override void ProcessDNSRecordStream(EndianBinaryReader propertyReader) {
            base.ProcessDNSRecordStream(propertyReader);

            this.Priority = propertyReader.ReadUInt16(isBigEndian: true);
            this.TargetName = base.ReadName(propertyReader);

            base.RecordData = string.Format("{0} {1}", this.Priority, this.TargetName);
        }

        protected override void ProcessResults() {

            try {
                if (string.IsNullOrWhiteSpace(this.DN)) {
                    base.ProcessResults();
                }

                var memoryStream = new MemoryStream(this.DNSRecord);
                using (var propertyReader = new EndianBinaryReader(memoryStream)) {
                    this.ProcessDNSRecordStream(propertyReader);
                }

                this.IsValid = !string.IsNullOrWhiteSpace(this.DN)
                    && this.ObjectClass.Any(x => x.Equals(ObjectCategoryShortName, StringComparison.OrdinalIgnoreCase))
                    && (this.RecordType == DNSRecordType.MX);
            }
            catch (Exception e) {
                Debug.WriteLine(string.Format("{0}  [ThreadID: {1}]  {2} Error: {3}", DateTime.Now.TimeOfDay, Thread.CurrentThread.ManagedThreadId, CustomExtensions.CurrentMethodName(), e.VerboseExceptionString()));
                throw;
            }

        }
        #endregion
    }
}
